package cn.iocoder.yudao.module.orderview.dal.redis.orderview;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.orderview.dal.redis.orderview.snapshot.OrderViewAggregationSnapshot;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

import static cn.iocoder.yudao.module.orderview.dal.redis.RedisKeyConstants.ORDER_VIEW_HOT_CACHE_PREFIX;
import static cn.iocoder.yudao.module.orderview.dal.redis.RedisKeyConstants.ORDER_VIEW_SNAPSHOT_PREFIX;
import static org.reflections.Reflections.log;

/**
 * {@link OrderViewAggregationSnapshot}  的 RedisDAO
 *
 * @author 徐煜东
 */
@Repository
public class OrderViewRedisDAO {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public OrderViewAggregationSnapshot get(String requestId) {
        String redisKey = formatKey(requestId);
        //log.info( "[get][获取缓存数据 key: {} hit: {}]", redisKey, true);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), OrderViewAggregationSnapshot.class);
    }

    public OrderViewAggregationSnapshot get0(String product) {
        String redisKey = formatKey0(product);
        //return  (OrderViewAggregationSnapshot) redisTemplate.opsForValue().get(redisKey);
        return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), OrderViewAggregationSnapshot.class);
    }

    public void set(OrderViewAggregationSnapshot orderView) {
        String redisKey = formatKey(orderView.getRequestId());
        //redisTemplate.opsForValue().set(redisKey, orderView, 5, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(orderView), 5, TimeUnit.MINUTES);
    }

    public void set0(OrderViewAggregationSnapshot orderView) {
        String redisKey = formatKey0(String.valueOf(orderView.getProductId()));
        //redisTemplate.opsForValue().set(redisKey, orderView, 5, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(orderView), 5, TimeUnit.MINUTES);

    }

    public void delete(String requestId) {
        String redisKey = formatKey(requestId);
        //redisTemplate.delete(redisKey);
        stringRedisTemplate.delete(redisKey);
    }


    private static String formatKey(String requestId) {
        return String.format(ORDER_VIEW_SNAPSHOT_PREFIX, requestId);
    }


    private static String formatKey0(String productId) {
        return String.format(ORDER_VIEW_HOT_CACHE_PREFIX, productId);
    }



}
